<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-03-17
 * Time: 21:48
 */
namespace App\Service;

use Swoole\Websocket\Server as WebsocketServer;

class WebSocketService
{
    protected $ws = null;
    public function __construct(array $config)
    {
        //实例化一个websocket服务器
        $this->ws = new WebsocketServer($config['host'], $config['port']);
        //添加一个监听端口，用户管理连接的客户端
        $this->ws->addlistener($config['manager_host'], $config['manager_port'], SWOOLE_SOCK_UDP);
        //设置参数
        $this->ws->set([
            'worker_num' => $config['worker_num'], //worker进程数 CPU核数的1-4倍
            'daemonize' => $config['daemonize']
        ]);
        //注册open message close 方法
        $this->ws->on('open', [$this, 'onOpen']);
        $this->ws->on('message', [$this, 'onMessage']);
        $this->ws->on('close', [$this, 'onClose']);
        //注册udp Packet 方法
        $this->ws->on('Packet', [$this, 'onPacket']);
    }

    public function onOpen($ws, $requeset)
    {
        $ws->push($requeset->fd, 'hello, welcome' . PHP_EOL);
    }

    public function onMessage($ws, $frame)
    {
        echo 'receive message ' . $frame->data . PHP_EOL;
        $ws->push($frame->fd, 'send message ' . date('Y-m-d H:i:s'));
    }

    public function onClose($ws, $fd)
    {
        echo $fd . ' client close' . PHP_EOL;
    }

    public function onPacket($ws, $data, $clientInfo)
    {
        $ws->sendto($clientInfo['address'], $clientInfo['port'], "Server ".$data);
        $ws->push(1, 'udp manager send massage');
    }

    public function start()
    {
        //启动服务
        $this->ws->start();
    }
}